package com.kyrie.lib_sys.application.timeApplys.service.impl;

import com.kyrie.lib_sys.application.timeApplys.service.LimitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class LimitServiceImpl implements LimitService {

    private static final String LIMIT_KEY_PREFIX = "limit:";
    private static final long WINDOW_SIZE_IN_SECONDS = 10; // 窗口大小为10秒
    private static final long MAX_REQUESTS = 100; // 10秒内最大请求数

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public boolean limitTest(String token) {

        // 构造Redis key
        String key = LIMIT_KEY_PREFIX + token;

        // 获取当前时间戳(毫秒)
        long now = System.currentTimeMillis();
        // 计算窗口开始时间(毫秒)
        long windowStart = now - WINDOW_SIZE_IN_SECONDS * 1000;

        // 使用Redis的ZSet数据结构
        // member为请求时间戳，score也为请求时间戳
        redisTemplate.opsForZSet().add(key, String.valueOf(now), now);

        // 移除窗口外的数据
        redisTemplate.opsForZSet().removeRangeByScore(key, 0, windowStart);

        // 获取当前窗口内的请求数
        Long count = redisTemplate.opsForZSet().zCard(key);

        // 设置key的过期时间，避免内存泄漏
        redisTemplate.expire(key, WINDOW_SIZE_IN_SECONDS + 1, TimeUnit.SECONDS);

        // 判断是否超过阈值
        return count != null && count > MAX_REQUESTS;

    }




}
